package com.example.viberapp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class ParseActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_parse);

	}
	
	public void sendJson(View view){
		System.out.println("Send JSONN");
		UserLocate userLocate = new UserLocate();
		userLocate.setCoordX("12222");
		userLocate.setCoordY("222222");
		
		String json = genereteJson(userLocate);
		
		callServer("send-json", json);
	} 
	
	public void getJson(View view){
		System.out.println("Get JSONN");
		callServer("get-json", "");
	}
	
	private String genereteJson(UserLocate userLocate){
		JSONObject jo = new JSONObject();
		JSONArray ja = new JSONArray();
		
		try{
			jo.put("coordX", userLocate.getCoordX());
			jo.put("coordY", userLocate.getCoordY());
			
		}catch(JSONException ex){
			
		}
		return jo.toString();
	}
	
	private UserLocate deGenereteJson(String data){
		UserLocate userLocate = new UserLocate();
		try{
			JSONObject jo = new JSONObject(data);
			userLocate.setCoordX(jo.getString("coordX"));
			userLocate.setCoordY(jo.getString("coordY"));
			
		}catch(JSONException ex){
			
		}
		Log.i("Script", "Coordenada X: " + userLocate.getCoordX());
		Log.i("Script", "Coordenada Y: " + userLocate.getCoordY());
		return userLocate;
	}
	
	private void callServer(final String method, final String data){
		new Thread(){
			public void run(){
				String resposta = HttpConnection.getSetDataWeb("http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5", method, data);
				Log.i("Script","Resposta: " + resposta);
				
				//IF for 
				if(data.isEmpty()){
					deGenereteJson(resposta);
				}
			}
			
		}.start();
		
	}
}
